package com.wanqing.community.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wanqing.community.bean.DepartmentBean;
import com.wanqing.community.bean.UserBean;
import com.wanqing.community.controller.util.BaseController;
import com.wanqing.community.manager.DepartmentManager;
import com.wanqing.community.manager.UserLoginManager;
import com.wanqing.community.util.ConditionParse;
import com.wanqing.community.util.KeyConstant;
import com.wanqing.community.util.NumberDealTools;
import com.wanqing.community.util.OrgNature;
import com.wanqing.community.util.StringTools;
import com.wanqing.community.util.UUID;
import com.wanqing.community.bean.JsonTree;

/**
 * 部门管理的控制层
 * All right reserved.
 * @version 
 */
@Controller
@RequestMapping("department")
public class DepartmentController extends BaseController{

	private static Logger log = Logger.getLogger(DepartmentController.class);
	
	@Resource
	private DepartmentManager departmentManager;
	@Resource
	private UserLoginManager userLoginManager;
	
	@RequestMapping(value="/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		
		//组织性质
		Map<Object,Object> orgNatureMap = OrgNature.map(); 
		mav.addObject("orgNatureMap", orgNatureMap);
		
		List<UserBean> list = this.userLoginManager.listUser();
		mav.addObject("users", list);
		mav.setViewName("sys/org/index");
		return mav;
	}
	
	/**
	 * <p>Description:查询部门信息<p>
	 * @modifiDate 2014-7-23
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=queryDepartment")
	public String queryDepartment(HttpServletRequest request,HttpServletResponse response){
		try{
			String tid = request.getParameter("tid");	
			String type = request.getParameter("type");
			String orgNature = request.getParameter("orgNature");
			
			
			ConditionParse condParse = new ConditionParse();
			if(StringTools.isEmptyOrNull(tid) || "root".equals(tid)){
				condParse.addCondition("PID", "=", -1);
			}else {
				condParse.addCondition("PID", "=", tid);
			}
			
			if(!StringTools.isEmptyOrNull(orgNature)){
				condParse.addCondition("orgNature", "=", orgNature);
			}
			condParse.addWhereStr();
//			ConditionParse condParse = new ConditionParse();
//			condParse.addCondition("PID", "=", tid);
			/*if(StringTools.isNotEmptyOrNull(type) && "user".equalsIgnoreCase(type)){
				condParse.addCondition("Length(ORGCODE)", "<=", 6);				
			}*/
//			condParse.addWhereStr();
			List<DepartmentBean> rows = this.departmentManager.queryDepartment(condParse);
			List<JsonTree> list = new ArrayList<JsonTree>();
			JsonTree tree = null;
			for (DepartmentBean depart : rows) {
				tree = new JsonTree();
				tree.setId(depart.getId());
				tree.setText(depart.getOrgName()+"("+depart.getManagerName()+")");
				tree.setPid(depart.getPid());
				tree.setLeaf(depart.isDleaf());
				boolean dleaf = depart.isDleaf();
				tree.setState(dleaf?"open":"closed");
				String state = tree.getState();
				if(StringTools.isNotEmptyOrNull(type) && "user".equalsIgnoreCase(type)){
					tree.setState("open");
				}
				
				tree.setCode(depart.getOrgCode());
				tree.setDepth(depart.getSeqnum());
				tree.setManagerId(depart.getOrgManagerId());
				tree.setOrgNature(depart.getOrgNature());
				tree.setOrgMemo(depart.getOrgMemo());
				String parentOrgName = depart.getParentOrgName();
//				if(!StringTools.isEmptyOrNull(parentOrgName)) {
					tree.setParentOrgName(parentOrgName);
//				}
				
				list.add(tree);
			}
			String json = StringTools.buildJson(list,false);				
			writeJson(response, json);
		}catch (Exception e) {
			log.error(e.toString());
		}
		return null;
	}
	
	/**
	 * <p>Description:添加部门信息<p>
	 * @modifiDate 2014-7-23
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=addDepartment")
	public String addDepartment(HttpServletRequest request,HttpServletResponse response){
		try{
			String pcode = StringTools.objectToString(request.getParameter("pcode"));			
			String orgName = StringTools.objectToString(request.getParameter("orgName"));
			String pid = StringTools.objectToString(request.getParameter("pid"));
			String orgManagerId = StringTools.objectToString(request.getParameter("orgManagerId"));	
			int orgNature = NumberDealTools.stringTranceInt(request.getParameter("orgNature"));
			String orgMemo = StringTools.objectToString(request.getParameter("orgMemo"));
			DepartmentBean department = new DepartmentBean();
			DepartmentBean parent = new DepartmentBean();
			parent.setId(pid);
			parent.setOrgCode(pcode);
			String id = UUID.uuId();
			department.setId(id);
			department.setPid(pid);
			department.setOrgName(orgName);
			department.setOrgNature(orgNature);
			department.setOrgMemo(orgMemo);
			department.setSeqnum(NumberDealTools.stringTranceInt(request.getParameter("seqnum"), 1));
			department.setOrgManagerId(orgManagerId);
			department.setParent(parent);
			boolean b = this.departmentManager.addDepartment(department);
			if(b){
				writeText(response,  KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());	
		}
		return null;
	}
	
	/**
	 * <p>Description:修改部门信息<p>
	 * @modifiDate 2014-7-23
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=updateDepartment")
	public String updateDepartment(HttpServletRequest request,HttpServletResponse response){
		try{
			String pid = StringTools.objectToString(request.getParameter("pidUpdate"));
			String orgName = StringTools.objectToString(request.getParameter("orgNameUpdate"));
			int i = orgName.indexOf("(");
			if(i>0) {
				orgName = orgName.substring(0,i);
			}
			String orgCode = StringTools.objectToString(request.getParameter("orgCodeUpdate"));
			String orgId = StringTools.objectToString(request.getParameter("orgIdUpdate"));
			String state = StringTools.objectToString(request.getParameter("dleafUpdate"));
			String orgManagerId = StringTools.objectToString(request.getParameter("orgManagerIdUpdate"));
			int orgNature = NumberDealTools.stringTranceInt(request.getParameter("orgNatureUpdate"));
			String orgMemo = StringTools.objectToString(request.getParameter("orgMemoUpdate"));
			boolean dleaf = true;
			if("closed".equalsIgnoreCase(state)){
				dleaf = false;
			}
			DepartmentBean department = new DepartmentBean();
			department.setPid(pid);
			department.setId(orgId);		
			department.setOrgName(orgName);
			department.setOrgCode(orgCode);
			department.setSeqnum(NumberDealTools.stringTranceInt(request.getParameter("seqnumUpdate"), 1));
			department.setOrgManagerId(orgManagerId);
			department.setOrgNature(orgNature);
			department.setOrgMemo(orgMemo);
			department.setDleaf(dleaf);
			boolean b = this.departmentManager.updateDepartment(department);
			if(b){
				writeText(response,  KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());	
		}
		return null;
	}
	
	/**
	 * <p>Description:删除部门信息<p>
	 * @modifiDate 2014-7-23
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=deleteDepartment")
	public String deleteDepartment(HttpServletRequest request,HttpServletResponse response){
		try{								
			String orgId = request.getParameter("id");
			boolean b = this.departmentManager.deleteDepartment(orgId);
			if(b){
				writeText(response,  KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());
		}
		return null;
	}
	
	/**
	 * <p>Description:查询当前节点的父节点<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=getParentNode")
	public String getParentNode(HttpServletRequest request,HttpServletResponse response) {
		String pid = StringTools.objectToString(request.getParameter("pid"));
		ConditionParse parse = new ConditionParse();
		parse.addCondition("pid","=",pid);
		parse.addWhereStr();
		List<DepartmentBean> departList = this.departmentManager.queryDepartment(parse);
		Map<String, Object> map = new HashMap<String, Object>();
		if(departList.size()>0) {
			DepartmentBean depart = departList.get(0);
			map.put("depart", depart);	
		}else {
			
		}
//		map.put("photosList", photosList);	
		String json = StringTools.buildJson(map);			
		writeJson(response, json);
		return null;
	}
	
	/**
	 * <p>Description:查询用户所属公司<p>
	 * <p>modifiContent:<p>
	 * @param departmentId
	 * @return
	 */
	public String getCompany(String departmentId) {
		
		String companyId = "";
		ConditionParse parse = new ConditionParse();
		parse.addCondition("id","=",departmentId);
		parse.addWhereStr();
		//用户所在部门信息
		List<DepartmentBean> departList = this.departmentManager.queryDepartment(parse);
		DepartmentBean depart =  departList.get(0);
		String pid = depart.getPid();
		ConditionParse pParse = new ConditionParse();
		pParse.addCondition("id","=",pid);
		pParse.addWhereStr();
		//用户所在部门父节点信息
		List<DepartmentBean> parentDepartList = this.departmentManager.queryDepartment(parse);
		if(parentDepartList.size()>0){
			DepartmentBean parentDepart =  parentDepartList.get(0);
			int orgNature = parentDepart.getOrgNature();
			if(orgNature == 10){
				companyId = parentDepart.getId();
			}else {
				getCompany(parentDepart.getPid());
			}
			
		}else {
			companyId =  departmentId;
		}
		
//		map.put("photosList", photosList);	
//		String json = StringTools.buildJson(map);			
//		writeJson(response, json);
		return companyId;
	}
}
